const router = require('express').Router();
const queryArticle = require('../db/queryArticle')

var fs = require("fs");
var path = require('path')
// 目录
// 当前页，上一页，下一页

async function hadleCatalog(res, res) {
  const result = await queryArticle.QueryAll()
  return result
}

function tmple(data){
  data.content = data.content.replace(/[&nbsp;]+/g,'<br/>&nbsp;&nbsp;&nbsp;&nbsp;')

  return `<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>${data.title}</title>
  </head>
  <body>
    <h3>${data.title}</h3>
    <p>${data.content}</p>
    <div>
      <a href="/catalog">目录</a>
      <a href="${data.number-1}">上一页</a>
      <a href="${data.number+1}">下一页</a>
    </div>
  </body>
  </html>`
}
function catalogTemplate(data){
  const list = []
  data.forEach((item)=>{
    list.push(`<div><a style="padding:30px" href="/atricle/${item.number}">${item.title}</a></div>`)
  })
  return `<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>目录</title>
  </head>
  <body>
    <h3>目录</h3>
    <div>${list.join('')}</div>
  </body>
  </html>`
}
async function HandleAtricle(req, res){
  const id = req.params.id
  const result = await queryArticle.QueryAllByNum(id)
  res.send(tmple(result))
}
async function catalog(req,res){
  const result = await hadleCatalog()
  res.send(catalogTemplate(result))
}

router.get('/catalog', hadleCatalog);
router.get('/atricle/:id', HandleAtricle);

module.exports = (app) => {
  // console.log('router')
  app.use('/catalog', catalog)
  app.use('/', router)
}